﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SaleSoft.Models;
using SaleSoft.Helper;
using SaleSoft.Constants;
using SaleSoft.Models.ScreenClient;
using Telerik.Web.Mvc;

namespace SaleSoft.Areas.administrator.Controllers
{
    public class WebMauController : BaseController {
        #region Properties Section
        SaleSoftEntities db = new SaleSoftEntities();
        #endregion

        #region Views Section
        public ActionResult Index()
        {
            WebMauScreenClient screen = new WebMauScreenClient();
            if (Session[ScreenClientConstants.WEB_MAU] != null) {
                try {
                    screen = (WebMauScreenClient)Session[ScreenClientConstants.WEB_MAU];
                } catch { }
            }
            Search(screen);
            ViewBag.id_trangthai = SelectListHelper.DSTrangThai(7, screen.id_trangthai);
            ViewBag.id_loaiweb = SelectListHelper.DSLoaiWeb(screen.id_loaiweb);
            return View(screen);
        }

        [HttpPost]
        public ActionResult Index ( WebMauScreenClient screen ) {
            Search(screen);
            ViewBag.id_trangthai = SelectListHelper.DSTrangThai(7, screen.id_trangthai);
            ViewBag.id_loaiweb = SelectListHelper.DSLoaiWeb(screen.id_loaiweb);
            return View(screen);
        }

        [GridAction]
        public ActionResult _Index () {
            WebMauScreenClient screen = new WebMauScreenClient();
            if (Session[ScreenClientConstants.WEB_MAU] != null) {
                try {
                    screen = (WebMauScreenClient)Session[ScreenClientConstants.WEB_MAU];
                } catch { }
            }
            Search(screen);
            return View(new GridModel(screen.DSWebMau));
        }

        public ActionResult Create()
        {
            ViewBag.id_loaiweb = SelectListHelper.DSLoaiWeb(null);
            ViewBag.id_ablum = SelectListHelper.DSAlbum(null);
            ViewBag.id_trangthai = SelectListHelper.DSTrangThai(5, null);
            return View();
        }

        public ActionResult Edit(int id)
        {
            ds_webmau _ds_webmau = db.ds_webmau.Single(d => d.id_webmau == id);
            ViewBag.id_loaiweb = SelectListHelper.DSLoaiWeb(_ds_webmau.id_loaiweb);
            ViewBag.id_ablum = SelectListHelper.DSAlbum(_ds_webmau.id_ablum);
            ViewBag.id_trangthai = SelectListHelper.DSTrangThai(5, _ds_webmau.id_trangthai);
            _ds_webmau.mota = HttpUtility.HtmlDecode(_ds_webmau.mota);
            return View(_ds_webmau);
        }
        #endregion

        #region CRUD Section
        [HttpPost]
        public ActionResult Create(Models.BaseClient.ds_webmau _ds_webmau, HttpPostedFileBase img)
        {
            if (ModelState.IsValid)
            {
                if (img != null && img.ContentLength > 0) {
                    if (img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".jpg" && img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".png") {
                        ViewData["error"] = "Accept JPGE and PNG file only";
                        ViewBag.id_loaiweb = SelectListHelper.DSLoaiWeb(_ds_webmau.id_loaiweb);
                        ViewBag.id_ablum = SelectListHelper.DSAlbum(_ds_webmau.id_ablum);
                        ViewBag.id_trangthai = SelectListHelper.DSTrangThai(5, _ds_webmau.id_trangthai);
                        return View(_ds_webmau);
                    } else {
                        string dt = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                        string fName = _ds_webmau.id_webmau + dt + img.FileName.Substring(img.FileName.LastIndexOf("."));
                        string SaveLocation = Server.MapPath("~\\UploadImages\\");
                        _ds_webmau.urlhinh = fName;
                        img.SaveAs(SaveLocation + fName);
                    }
                }
                ds_webmau save = new ds_webmau();
                ObjectHelper.Copy(_ds_webmau, save);

                db.ds_webmau.AddObject(save);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.id_loaiweb = SelectListHelper.DSLoaiWeb(_ds_webmau.id_loaiweb);
            ViewBag.id_ablum = SelectListHelper.DSAlbum(_ds_webmau.id_ablum);
            ViewBag.id_trangthai = SelectListHelper.DSTrangThai(5, _ds_webmau.id_trangthai);
            _ds_webmau.mota = HttpUtility.HtmlDecode(_ds_webmau.mota);
            return View(_ds_webmau);
        }

        [HttpPost]
        public ActionResult Edit(Models.BaseClient.ds_webmau _ds_webmau, HttpPostedFileBase img)
        {
            if (ModelState.IsValid)
            {
                ds_webmau old = db.ds_webmau.Single(p => p.id_webmau == _ds_webmau.id_webmau);
                if (img == null || img.ContentLength == 0) { // khong lam gi ca
                    _ds_webmau.urlhinh = old.urlhinh;
                } else if (old.urlhinh == null && img != null && img.ContentLength > 0) { // hinh cu khong co, luu hinh moi
                    //save image
                    if (img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".jpg" && img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".png") {
                        ViewBag.id_loaiweb = SelectListHelper.DSLoaiWeb(_ds_webmau.id_loaiweb);
                        ViewBag.id_ablum = SelectListHelper.DSAlbum(_ds_webmau.id_ablum);
                        ViewBag.id_trangthai = SelectListHelper.DSTrangThai(5, _ds_webmau.id_trangthai);
                        ViewData["error"] = "Accept JPGE and PNG file only";
                        _ds_webmau.mota = HttpUtility.HtmlDecode(_ds_webmau.mota);
                        return View(_ds_webmau);
                    }
                    string dt = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                    string fName = _ds_webmau.id_webmau + dt + img.FileName.Substring(img.FileName.LastIndexOf("."));
                    string SaveLocation = Server.MapPath("~\\UploadImages\\");
                    try {
                        img.SaveAs(SaveLocation + fName);   //save new file
                        _ds_webmau.urlhinh = fName;              //save file name to entity                    
                    } catch (Exception e) { ViewData["error"] = e.Message; return View(_ds_webmau); }
                } else if (old.urlhinh != null && img != null && img.ContentLength > 0) { // co hinh cu, co hinh moi 
                    string oldFile = Server.MapPath("/UploadImages/") + old.urlhinh;
                    //xoa file cu
                    if (System.IO.File.Exists(oldFile)) {
                        try {
                            System.IO.File.Delete(oldFile);
                        } catch (Exception) {
                        }
                    }
                    //luu file moi
                    if (img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".jpg" && img.FileName.Substring(img.FileName.LastIndexOf(".")).ToLower() != ".png") {
                        ViewData["error"] = "Accept JPGE and PNG file only";
                        return View(_ds_webmau);
                    }
                    string dt = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second;
                    string fName = _ds_webmau.id_webmau + dt + img.FileName.Substring(img.FileName.LastIndexOf("."));
                    string SaveLocation = Server.MapPath("~\\UploadImages\\");
                    try {
                        img.SaveAs(SaveLocation + fName);   //save new file
                        _ds_webmau.urlhinh = fName;              //save file name to entity                    
                    } catch (Exception e) {
                        ViewData["error"] = e.Message;
                        ViewBag.id_loainoidung = SelectListHelper.DSloainoidung(_ds_webmau.id_loaiweb);
                        ViewBag.id_trangthai = SelectListHelper.DSTrangThai(5, _ds_webmau.id_trangthai);
                        ViewBag.id_album = SelectListHelper.DSAlbum(_ds_webmau.id_ablum);
                        return View(_ds_webmau);

                    }
                }
                ds_webmau save = db.ds_webmau.Single(p => p.id_webmau == _ds_webmau.id_webmau);
                ObjectHelper.Copy(_ds_webmau, save);
                db.ObjectStateManager.ChangeObjectState(save, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.id_loaiweb = SelectListHelper.DSLoaiWeb(_ds_webmau.id_loaiweb);
            ViewBag.id_ablum = SelectListHelper.DSAlbum(_ds_webmau.id_ablum);
            ViewBag.id_trangthai = SelectListHelper.DSTrangThai(5, _ds_webmau.id_trangthai);
            _ds_webmau.mota = HttpUtility.HtmlDecode(_ds_webmau.mota);
            return View(_ds_webmau);
        }

        public ActionResult Delete(int id)
        {
            ds_webmau _ds_webmau = db.ds_webmau.Single(d => d.id_webmau == id);
            
            //Delete images
            string path = Server.MapPath("~//UploadImages//") + _ds_webmau.urlhinh;
            FileHelper.DeleteFile(path);
            db.ds_webmau.DeleteObject(_ds_webmau);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        #endregion

        #region Helper Section
        private void Search ( WebMauScreenClient screen ) {
            if (screen == null) screen = new WebMauScreenClient();
            DateTime? tmp = (screen.capnhatden.HasValue) ? screen.capnhatden.Value : screen.capnhatden;
            var data = db.ds_webmau.Where( p =>
                    (screen.tenwebmau == null || p.tenwebmau.Contains(screen.tenwebmau)) &&
                    (screen.id_loaiweb == null || p.id_loaiweb == screen.id_loaiweb) &&
                    (screen.id_trangthai == null || p.id_trangthai == screen.id_trangthai) && 
                    (screen.giatu == null || p.gia >= screen.giatu) &&
                    (screen.giaden == null || p.gia <= screen.giaden) &&
                    (screen.capnhattu == null || p.ngaycapnhat >= screen.capnhattu) && 
                    (screen.capnhatden == null || p.ngaycapnhat <= tmp)
                );
            screen.DSWebMau.Clear();
            foreach (ds_webmau webmau in data) {
                Models.BaseClient.ds_webmau client = new Models.BaseClient.ds_webmau();
                ObjectHelper.Copy(webmau, client);
                client.TenAlbum = db.ds_ablum.Single(o => o.id_ablum == client.id_ablum).tenablum;
                client.HinhAlbum = db.ds_ablum.Single(o => o.id_ablum == client.id_ablum).anhbia;
                client.TenLoaiWeb = db.loai_web.Single(o => o.id_loaiweb== client.id_loaiweb).tenloaiweb;
                client.TenTrangThai = db.ds_trangthai.Single(p => p.id_trangthai == client.id_trangthai).tentrangthai;
                screen.DSWebMau.Add(client);
            }
        }
        #endregion
    }
}
